import axios from 'axios' // 引入axios
import config from '@/utils/http/http-config'
import authUtils from "~/utils/auth";

const instance = axios.create({
    baseURL: config.domain,
    timeout: 60000,
})


// 请求拦截器
instance.interceptors.request.use(function (config) {
    const token = authUtils.getToken()
    config.headers.Authorization = token
    return config
}, function (error) {
    return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(function (response) {
    console.log('得到的响应数据', response)
    return response
}, function (error) {
    console.log('响应错误', error)
    console.log('----------')
    if (error.response.status === 401) {
        if (process.client) {
            authUtils.clearAuthInfo()
            const href = window.location.href
            let params = href.split('?')[1]
            // window.open('/login?back_url=' + encodeURIComponent(window.location.pathname + (params === undefined ? '' : ('?' + params))))
            const router = useRouter()
            router.push('/login?back_url=' + encodeURIComponent(window.location.pathname + (params === undefined ? '' : ('?' + params))))
        }
    }
    return Promise.reject(error)
})

// get请求
export function httpGet(url, data = {}) {
    return new Promise((resolve, reject) => {
        instance
            .get(url, {
                params: data
            })
            .then((response) => {
                resolve(response.data)
            })
            .catch((err) => {
                reject(err)
            })
    })
}

// post请求
export function httpPost(url, data = {}) {
    return new Promise((resolve, reject) => {
        instance.post(url, data).then(
            (response) => {
                resolve(response.data)
            },
            (err) => {
                reject(err)
            }
        )
    })
}

export function httpDel(url, data = {}) {
    return new Promise((resolve, reject) => {
        instance.delete(url, data).then(
            (response) => {
                resolve(response.data)
            },
            (err) => {
                reject(err)
            }
        )
    })
}

export function httpPatch(url, data = {}) {
    return new Promise((resolve, reject) => {
        instance.patch(url, data).then(
            (response) => {
                resolve(response.data)
            },
            (err) => {
                reject(err)
            }
        )
    })
}

export function postForm(url, formData) {
    return new Promise((resolve, reject) => {
        instance.post(url, formData, {
            'Content-type': 'multipart/form-data'
        }).then(
            (response) => {
                resolve(response.data)
            },
            (err) => {
                reject(err)
            }
        )
    })
}

export function genFileUrl(key){
    return config.cosDomain + '/' + key
}